package poi.utils;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Slf4j
public class PoiUtils {

    /**
     * 创建Excel
     *
     * @param title  文件第一行的标题  会合并居中
     * @param sheetName sheet名
     * @param isCreateHeader 是否出现第一行的title
     * @param pojoClass  数据对应的实体类
     * @param data  具体数据
     * @param response
     * @param fileName 文件名
     */
    public static void exportExcel(String title,
                                   String sheetName,
                                   boolean isCreateHeader,
                                   Class<?> pojoClass,
                                   List<?> data,
                                   HttpServletResponse response,
                                   String fileName) {

        ExportParams exportParams = new ExportParams(title, sheetName);
        exportParams.setCreateHeadRows(isCreateHeader);

        Workbook workbook = ExcelExportUtil.exportExcel(exportParams, pojoClass, data);
        if (workbook == null) {
            System.out.println("导出失败，文件为空！");
            return;
        }
        downloadExcel(response, fileName, workbook);
    }

    /**
     * 下载Excel
     */
    private static void downloadExcel(HttpServletResponse response, String fileName, Workbook workbook) {
        // 设置响应实体的编码格式
        response.setCharacterEncoding("UTF-8");
        // 通知浏览器使用什么软件可以打开此文件
        response.setHeader("content-Type", "application/vnd.ms-excel;charset=" + "UTF-8");
        // 下载文件的默认名称
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")+".xls");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        try {
            workbook.write(response.getOutputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 读取文件流导入
     * @param inputStream
     * @param pojoClass
     * @throws Exception
     */
    public static List importStreamExcel(InputStream inputStream, Class<?> pojoClass) throws Exception {
        return ExcelImportUtil.importExcel(inputStream, pojoClass,new ImportParams());
    }

    /**
     * 读取文件导入
     * @param file
     * @param pojoClass
     */
    public static List importFileExcel(File file, Class<?> pojoClass) {
        return ExcelImportUtil.importExcel(file, pojoClass,new ImportParams());
    }

}
